<template>
	<div>
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>用户管理</el-breadcrumb-item>
			<el-breadcrumb-item>用户列表</el-breadcrumb-item>
		</el-breadcrumb>
		<el-card class="box-card">
			<el-row>
				<el-col :span="7">
					<el-input placeholder="请输入内容" v-model="queryInfo.querys" clearable @clear="getMgByPage">
						<el-button slot="append" icon="el-icon-search" @click="getMgByPage"></el-button>
					</el-input>
				</el-col>
				<el-col :span="2" class="addUserButn">
					<!-- type="primary" 添加样式，这里为蓝色 -->
					<el-button type="primary" @click="addUserFormVisible = true">添加用户</el-button>
				</el-col>
			</el-row>
		<el-table :data="managerList" border style="width: 100%">
				<el-table-column prop="username" label="姓名">
				</el-table-column>
				<el-table-column prop="email" label="邮箱">
				</el-table-column>
				<el-table-column prop="mobile" label="电话">
				</el-table-column>
				<el-table-column prop="role_name" label="角色">
				</el-table-column>
				<el-table-column prop="mg_state" label="状态">
					<!-- 插槽，用于父组件向子组件传递数据 
						父组件的数据会传递给scope
						scope.row 获得对应行的全部数据
					-->
					<template slot-scope = "scope">
						<el-switch v-model="scope.row.mg_state" @change="setMgStatus(scope.row)"></el-switch>
					</template>
				</el-table-column>
			<el-table-column label="操作" width="180px">
				<template slot-scope="scope">
					<el-tooltip class="item" effect="dark" content="编辑用户" placement="top" >
						<el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row)"></el-button>
					</el-tooltip>
					<el-tooltip class="item" effect="dark" content="删除用户" placement="top">
						<el-button type="danger" size="mini" icon="el-icon-delete" @click="delUsers(scope.row.id)"></el-button>
					</el-tooltip>
					<el-tooltip class="item" effect="dark" content="分配权限" placement="top">
						<el-button type="warning" size="mini" icon="el-icon-setting" @click="devidePerm(scope.row)"></el-button>
					</el-tooltip>
				</template>
			</el-table-column>
		</el-table>
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="queryInfo.pagenum" :page-sizes="[2, 5, 8, 10]" :page-size="queryInfo.pagesize"
				layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</el-card>
		<el-dialog title="添加用户" :visible.sync="addUserFormVisible" @close="resetAddUserForm">
			<el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserForm">
				<el-form-item label="用户名" prop="username">
					<el-input v-model="addUserForm.username"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="userpwd">
					<el-input v-model="addUserForm.userpwd" show-password></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="useremail">
					<el-input v-model="addUserForm.useremail"></el-input>
				</el-form-item>
				<el-form-item label="手机" prop="usermobile">
					<el-input v-model="addUserForm.usermobile"></el-input>
				</el-form-item>
			</el-form>
		 <div slot="footer" class="dialog-footer">
				<el-button @click="addUserFormVisible = false">取 消</el-button>
		 	<el-button type="primary" @click="addUser">确 定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="编辑用户" :visible.sync="editUserFormVisible" @close="resetEditUserForm">
			<el-form :model="editUserForm" :rules="editUserFormRules" ref="editUserForm">
				<el-form-item label="用户名" prop="username">
					<el-input v-model="editUserForm.username" disabled></el-input>
				</el-form-item>
				<!-- <el-form-item label="密码" prop="userpwd">
					<el-input v-model="editUserForm.userpwd" show-password></el-input>
				</el-form-item> -->
				<el-form-item label="邮箱" prop="useremail">
					<el-input v-model="editUserForm.useremail"></el-input>
				</el-form-item>
				<el-form-item label="手机" prop="usermobile">
					<el-input v-model="editUserForm.usermobile"></el-input>
				</el-form-item>
			</el-form>
		 <div slot="footer" class="dialog-footer">
				<el-button @click="editUserFormVisible = false">取 消</el-button>
		 	<el-button type="primary" @click="editUser">确 定</el-button>
			</div>
		</el-dialog>
		<!-- 分配权限 -->
		<el-dialog title="分配权限" :visible.sync="deviPermDialogVisible" width="50%" @close="resetSelect">
			<div >
				<p>当前的用户： {{deviPerm.userName}}</p>
				<p>当前的角色： {{deviPerm.userRole}}</p>
				<p>分配新角色： 
					<el-select v-model="roleId" placeholder="请选择">
					    <el-option
					      v-for="item in deviPerm.options"
					      :key="item.role_id"
					      :label="item.role_name"
					      :value="item.role_id">
					    </el-option>
					  </el-select>
				</p>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="deviPermDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="alloaPerm">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		data() {
			let checkEmail = (rule, value, callback) => {
				let reqEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
				if (reqEmail.test(value)) {
					return callback();
				}
				return callback('请输入合法的邮箱');
			}
			let checkMobile = (rule, value, callback) => {
				let reqMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
				if (reqMobile.test(value)) {
					return callback();
				}
				return callback('请输入正确的手机号');
			}
			return {
				managerList: [],
				queryInfo: {
					querys: '',
					pagenum: 1,
					pagesize: 2,
				},
				total: null,
				addUserFormVisible: false,
				addUserForm: {
					username: '',
					userpwd: '',
					useremail: '',
					usermobile: ''
				},
				addUserFormRules: {
					username: [
						{required: true,message: '请输入用户名',trigger: 'blur'},
						{min: 3,max: 10,message: '长度在 3 到 10 个字符',trigger: 'blur'}
					],
					userpwd: [
						{required: true,message: '请输入密码',trigger: 'blur'},
						{min: 6,max: 15,message: '长度在 6 到 15 个字符',trigger: 'blur'}
					],
					useremail: [
						{required: true,message: '请输入邮箱',trigger: 'blur'},
						{validator: checkEmail,trigger: 'blur'}
					],
					usermobile: [
						{required: true,message: '请输入手机号',trigger: 'blur'},
						{validator: checkMobile,trigger: 'blur'}
					]
				},
				editUserFormVisible:false,
				editUserForm: {
					userId: '',
					username: '',
					useremail: '',
					usermobile: ''
				},
				editUserFormRules:{
					useremail: [
						{required: true,message: '请输入邮箱',trigger: 'blur'},
						{validator: checkEmail,trigger: 'blur'}
					],
					usermobile: [
						{required: true,message: '请输入手机号',trigger: 'blur'},
						{validator: checkMobile,trigger: 'blur'}
					]
				},
				deviPermDialogVisible:false,
				deviPerm:{
					userId: '',
					userName: '',
					userRole: '',
					options: []
				},
				roleId: ''
			}
		},
		methods: {
			async getMgByPage() {
				let {
					data: res
				} = await this.$http.get('/manager/users', {
					params: this.queryInfo
				})
				if (res.meta.status !== 200) return this.$message.error('用户列表获取失败')
				// console.log(res);
				this.managerList = res.data.users;
				this.total = res.data.total;
				this.queryInfo.pagenum = res.data.pagenum;
			},
			handleSizeChange(newSize) {
				this.queryInfo.pagesize = newSize;
				this.getMgByPage();
			},
			handleCurrentChange(newPage) {
				this.queryInfo.pagenum = newPage;
				this.getMgByPage();
			},
			addUser() {
				// 进行表单预验证
				this.$refs.addUserForm.validate(async valid => {
					if (!valid) return;
					let {data: res} = await this.$http.post('/manager/users', this.addUserForm)
					if (res.meta.status !== 200) {
						return this.$message.error(res.meta.msg);
					}
					this.$message.success(res.meta.msg);
					this.getMgByPage()
					this.addUserFormVisible = false;
				})
			},
			resetAddUserForm() {
				// 重置添加表单   关闭之后重置表单
				this.$refs.addUserForm.resetFields();
			},
			async setMgStatus(mgInfo){
				// 修改用户的状态   动态路由传参
				/* 
				 put 请求  是restFul编码风格，规定发送请求时，请求方式不能要么get要么post
						  要求增删改查的请求要用不同的请求方式
						  删 delete,改 put ,查get/post，增 post
				 */
				let {data:res} = await this.$http.put(`/manager/users/${mgInfo.id}/state/${mgInfo.mg_state}`)
				if(res.meta.status !==200){
					// 失败后，把状态还原
					mgInfo.mg_state = !mgInfo.mg_state
					
					return this.$message.error(res.meta.msg)
				}
				this.$message.success(res.meta.msg);
			},
			resetEditUserForm(){
				this.$refs.editUserForm.resetFields()
			},
			showEditDialog(mgInfo){
				// 把接收到的数据，填充到表单里
				this.editUserForm.userId = mgInfo.id;
				this.editUserForm.username = mgInfo.username;
				this.editUserForm.useremail = mgInfo.email;
				this.editUserForm.usermobile = mgInfo.mobile;
				this.editUserFormVisible = true;
			},
			editUser(){
				// 预验证
				this.$refs.editUserForm.validate(async valid =>{
					if(!valid) return;
					let {data:res} = await this.$http.put('/manager/editUsers',this.editUserForm);
					if(res.meta.status !==200) return this.$message.error(res.meta.msg);
					this.$message.success(res.meta.msg);
					this.editUserFormVisible = false;
				})
			},
			async delUsers(uid){
				const resultConfirm = await this.$confirm(
				'此操作将永久删除用户,是否继续',
				'提示',
					{
					confirmButtonText: '确定',
				    cancleButtonText: '取消',
				    type: 'warning'
					},
				).catch(err => err)
				if(resultConfirm !== 'confirm'){
					return this.$message.info('此操作已取消');
				}
				let {data:res} = await this.$http.delete(`/manager/users/${uid}`);
				if(res.meta.status !==200) return this.$message.error(res.meta.msg);
				this.$message.success(res.meta.msg);
				this.getMgByPage();
			},
			async devidePerm(mgInfo){
				this.deviPerm.userId = mgInfo.id;
				this.deviPerm.userName = mgInfo.username;
				this.deviPerm.userRole = mgInfo.role_name;
				let {data:res} = await this.$http.get('/role/roles');
				if(res.meta.status !== 200)return this.$message.error('角色管理，姓名列表获取失败');
				this.deviPerm.options = res.data;
				this.deviPermDialogVisible = true;
			},
			resetSelect(){
				// 一旦关闭就把select重置
				this.roleId = '';
				this.deviPerm.options = [];
			},
			async alloaPerm(){
				// console.log(this.roleId,this.deviPerm.userId);
				let {data:res} = await this.$http.put(`/manager/users/${this.deviPerm.userId}/role/${this.roleId}`);
				if(res.meta.status !== 200) return this.$message.error(res.meta.msg);
				this.$message.success(res.meta.msg);
				this.getMgByPage()
				this.deviPermDialogVisible = false;
			}
		},
		created() {
			this.getMgByPage()
		}
	}
</script>

<style lang="scss">
	.addUserButn {
		margin-left: 20px;
	}
</style>
